package com.kun.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.dto.UserDto;
import com.kun.entity.SysRole;
import com.kun.entity.SysUser;
import com.kun.entity.SysUserRole;
import com.kun.mapper.SysRoleMapper;
import com.kun.mapper.SysUserMapper;
import com.kun.mapper.SysUserRoleMapper;
import com.kun.service.SysUserService;
import com.kun.transform.TableData;
import com.kun.transform.TransformUtil;
import com.kun.util.PasswordUtil;
import com.kun.dto.SysUserDTO;
import com.kun.vo.SysUserVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kun.li
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveUser(UserDto userDto) {
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(userDto, sysUser);
        sysUser.setPassword(PasswordUtil.getInstance().encode(userDto.getPassword()));
//        sysUser.setPassword(userDto.getPassword());
        //保存用户和部门
        baseMapper.insert(sysUser);
        //保存用户对应角色
        List<String> roleList = userDto.getRole();
        if (CollUtil.isNotEmpty(roleList)) {
            roleList.stream().map(roleId -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(sysUser.getUserId());
                sysUserRole.setRoleId(roleId);
                return sysUserRole;
            }).forEach(sysUserRoleMapper::insert);
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUser(UserDto userDto) {
        // 更新用户信息和部门信息 部门ID为 1,2
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(userDto, sysUser);
        String password = userDto.getPassword();
        if (StrUtil.isNotEmpty(password)) {
            sysUser.setPassword(PasswordUtil.getInstance().encode(password));
        }else {
            SysUser user = sysUserMapper.selectById(userDto.getUserId());
            sysUser.setPassword(user.getPassword());
        }
        baseMapper.updateById(sysUser);
        // 更新角色信息
        sysUserRoleMapper.delete(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userDto.getUserId()));
        userDto.getRole().stream().map(roleId -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userDto.getUserId());
            sysUserRole.setRoleId(roleId);
            return sysUserRole;
        }).forEach(sysUserRoleMapper::insert);
        return Boolean.TRUE;
    }

    @Override
    public SysUser getSysUserAndRole(String userId) {
        SysUser sysUser = baseMapper.selectById(userId);
        List<SysRole> sysRoles = sysRoleMapper.selectSysRole(userId);
        sysUser.setRoles(sysRoles);
        return sysUser;
    }

    @Override
    public Page<SysUserVO> getUserTableData(SysUserDTO sysUserDTO) {
        Long page = sysUserDTO.getPage();
        Long size = sysUserDTO.getSize();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        Page<SysUserVO> sysUserVOPage = sysUserMapper.selectUserPage(Page.of(page, size), queryWrapper);
        List<SysUserVO> records = sysUserVOPage.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            records.forEach(sysUser -> {
                sysUser.setPassword(null);
                List<SysRole> sysRoles = sysRoleMapper.selectSysRole(sysUser.getUserId());
                sysUser.setRoles(sysRoles);
            });
            sysUserVOPage.setRecords(records);
        }
        return sysUserVOPage;
    }
}
